package com.ztesoft.zsmart.zcm.monitor.utils;

import com.ztesoft.zsmart.core.log.ZSmartLogger;
import com.ztesoft.zsmart.core.tools.log.LogSanitizerConfig;
import com.ztesoft.zsmart.core.tools.log.LogSanitizerTool;
import com.ztesoft.zsmart.core.tools.log.SensitiveWord;
import com.ztesoft.zsmart.core.utils.StringUtil;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;

/**
 * 脱敏帮助类
 *
 * @Author FJJ
 * @Date 2020/12/9
 */
public final class DesensitizeHelper {

    private static final ZSmartLogger logger = ZSmartLogger.getLogger(CommonUtil.class);

    private DesensitizeHelper() {

    }

    /**
     * @param str 脱敏字符串,为null则不脱敏
     * @return
     */
    public static String desensitizeString(String str, List<SensitiveWord> sensitiveWordsList) {

        if (StringUtil.isEmpty(str)) {
            return str;
        }

        logger.debug("[Desense Tool] Set Config Start.");
        LogSanitizerConfig config = LogSanitizerTool.defaultConfig();
        // startPattern为默认值
        config.setStartPattern(".");

        logger.debug("[Desense Tool] Set Config Completely.");
        SensitiveWord[] words = new SensitiveWord[sensitiveWordsList.size()];
        config.addSensitiveWords(sensitiveWordsList.toArray(words));

        try (ByteArrayOutputStream output = new ByteArrayOutputStream();
             InputStream input = new ByteArrayInputStream(str.getBytes("UTF-8"))) {
            logger.debug("[Desense Tool] Original Str: " + str);
            logger.debug("[Desense Tool] Do Desense String Start.");
            LogSanitizerTool.desensitize(input, output, config);
            str = output.toString();
            logger.debug("[Desense Tool] Do Desense String Completely.");
        }
        catch (IOException e) {
            logger.error(e);
        }

        return str;
    }


}
